/*
 * @lc app=leetcode.cn id=297 lang=typescript
 *
 * [297] 二叉树的序列化与反序列化
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

//  思路：BFS
//  参考：https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/solution/shou-hui-tu-jie-gei-chu-dfshe-bfsliang-chong-jie-f/


/*
 * Encodes a tree to a single string.
 */
function serialize(root: TreeNode | null): string {
    const queue = [root]
    const res = []

    while (queue.length) {
        const node = queue.shift()
        if (node) {
            res.push(node.val)
            queue.push(node.left)
            queue.push(node.right)
        } else {
            res.push('#')
        }
    }
    return res.join(',')
};

/*
 * Decodes your encoded data to tree.
 */
function deserialize(data: string): TreeNode | null {
    if (data === '#') return null
    const list = data.split(',').map(str => str === '#' ? '#' : parseInt(str))
    const root = new TreeNode(list[0] === '#' ? undefined : list[0])
    const queue = [root]
    let index = 1

    while (index < list.length) {
        const node = queue.shift()

        const leftVal = list[index]
        const rightVal = list[index + 1]

        if (leftVal !== '#') {
            const leftNode = new TreeNode(leftVal)
            node!.left = leftNode
            queue.push(leftNode)
        }
        if (rightVal !== '#') {
            const rightNode = new TreeNode(rightVal)
            node!.right = rightNode
            queue.push(rightNode)
        }
        index += 2
    }

    return root
};


/**
 * Your functions will be called as such:
 * deserialize(serialize(root));
 */
// @lc code=end

import { TreeNode } from './type'
const root = TreeNode.buildTree([1, 2, 3, null, null, 4, 5])
const ser = serialize(root)
const tree = deserialize(ser)
console.log(ser, TreeNode.printTree(tree))
